export function isMiniProgram() {
  const userAgent = navigator.userAgent.toLowerCase();
  return userAgent.indexOf('miniprogram') !== -1; // 如果是小程序，userAgent 中会包含 "miniprogram"
}
export function downloadFiles(name: string, url: string): void {
  console.log('开始下载文件...', name, url);
  
  fetch(url)
    .then(response => {
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return response.blob();
    })
    .then(blob => {
      // 创建 Blob URL
      const objectURL = URL.createObjectURL(blob);
      // 创建隐藏的 <a> 元素
      const link = document.createElement('a');
      link.href = objectURL;
      link.download = name || 'downloaded-file';
      link.style.display = 'none';

      document.body.appendChild(link);
      link.click(); // 模拟点击

      // 清理工作
      document.body.removeChild(link);
      URL.revokeObjectURL(objectURL); // 释放 Blob URL
    })
    .catch(error => {
      console.error('下载失败:', error);
    });
}


/* 判断一个字符串是否可以被 JSON.parse 解析为 JSON */
export const isJSON = (str: string): boolean => {
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    return false;
  }
}

export const deepCopy = <T>(obj: Readonly<T>): T => {
  if (Array.isArray(obj)) {
    const copiedArray: any[] = [];
    for (const item of obj) {
      copiedArray.push(deepCopy(item));
    }
    return copiedArray as T;
  } else if (typeof obj === 'object' && obj !== null) {
    const copiedObj: any = {};
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        copiedObj[key] = deepCopy(obj[key]!);
      }
    }
    return copiedObj as T;
  } else {
    return obj;
  }
}
export const buildTree = (lists: any[], str: string) => {
  /* str 表示父级id对应的字段名 */
  let treeMap: any = {}, tree: any = [];
  lists?.forEach(item => {
    let obj = treeMap[item.id];
    treeMap[item.id] = {
      ...item,
      children: obj?.children || item.children || [],
    }
    if (item[str]) {
      if (!treeMap[item[str]]) {
        treeMap[item[str]] = {children: []};
      }
      treeMap[item[str]].children.push(treeMap[item.id]);
    } else {
      tree.push(treeMap[item.id]);
    }
  });
  return tree
}